//
//  AKLookups.m
//  AKLookups
//
//  Created by Andrey Kadochnikov on 17.05.14.
//  Copyright (c) 2014 Andrey Kadochnikov. All rights reserved.
//

#import "AKLookups.h"
#import "NSString+StringSizeWithFont.h"
#import "AKLookupsListViewController.h"

@interface AKLookups ()
{
	NSArray*						_items;
	UIImageView* 					_arrowIndicator; //TODO easy color customization and highlighted state needed
    UIImageView* 					_logoImage; //TODO easy color customization and highlighted state needed
    UILabel*                       _titleDetail;
	BOOL 							_isOpened;
	AKDropdownViewController*		_lookupVC;
}
@end

@implementation AKLookups

-(instancetype)initWithLookupViewController:(AKDropdownViewController*)viewController
{
	NSAssert(viewController, @"viewController is mandatory");
	NSAssert([viewController isKindOfClass:[AKDropdownViewController class]], @"viewController must be a subclass of AKDropdownViewController");
	self = [super init];
	if (self){
		_lookupVC = viewController;
		_selectedItem = nil;
		[self addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
		
		_arrowIndicator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"selector_btn_arrow"]];
        _arrowIndicator.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		_arrowIndicator.contentMode = UIViewContentModeRight;
        _logoImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _logoImage.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _logoImage.contentMode = UIViewContentModeCenter;
        _titleDetail = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,20,20)];
        _titleDetail.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _titleDetail.contentMode = UIViewContentModeCenter;
        _titleDetail.textColor = [UIColor orangeColor];
        _titleDetail.textAlignment = NSTextAlignmentRight;
		[self addSubview:_arrowIndicator];
        [self addSubview:_logoImage];
        [self addSubview:_titleDetail];
		[self selectItem:_selectedItem];
	}
	return self;
}


-(void)pressed
{
	if (!_isOpened){
		[self openLookup];
	} else {
		[self closeLookup];
	}
}

-(void)selectItem:(id<AKLookupsCapableItem>)item
{
	_selectedItem = item;
	[self setTitle:[(id<AKLookupsCapableItem>)item lookupTitle] forState:UIControlStateNormal];
    [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    if ([(id<AKLookupsCapableItem>)item lookupImage] != nil && [(id<AKLookupsCapableItem>)item lookupDetailTitle] == nil) {

        [self setTitleEdgeInsets:UIEdgeInsetsMake(0,0, 0,20)];
    }
    else{
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0,0, 0,0)];

    }
}

-(void)layoutSubviews
{
	[super layoutSubviews];
	NSString *title;
	title = [_selectedItem lookupTitle];
    _logoImage.image = [_selectedItem lookupImage];
    _titleDetail.text = [_selectedItem lookupDetailTitle];
    if (_logoImage.image != nil &&  _titleDetail.text == nil) {
//        _logoImage.frame =CGRectMake(self.titleLabel.frame.origin.x-18,CGRectGetMidY((self.bounds)),1,1);
//
//        CGFloat x = CGRectGetMidX(self.bounds) +[title sizeWithMyFont:self.titleLabel.font].width/2-5;
//         _arrowIndicator.frame = CGRectMake(x + 20 +self.titleEdgeInsets.left - self.titleEdgeInsets.right,CGRectGetMidY(self.bounds) - 4 + self.titleEdgeInsets.top/2 - self.titleEdgeInsets.bottom/2,10,10);
        
        _logoImage.frame = CGRectMake(8,self.frame.size.height/8,35,35);
        self.titleLabel.frame = CGRectMake(_logoImage.frame.origin.x + _logoImage.frame.size.width+3,self.frame.size.height/3,self.titleLabel.frame.size.width,self.titleLabel.frame.size.height);
        
        _arrowIndicator.frame = CGRectMake(self.frame.size.width-self.frame.origin.x-_arrowIndicator.frame.size.width,(self.frame.size.height -_arrowIndicator.frame.size.height)/2 ,10,10);

    }
    else if(_logoImage.image != nil && _titleDetail.text != nil){
        _logoImage.frame = CGRectMake(8,self.frame.size.height/8,35,35);
        self.titleLabel.frame = CGRectMake(_logoImage.frame.origin.x + _logoImage.frame.size.width+3,self.frame.size.height/3,self.titleLabel.frame.size.width,self.titleLabel.frame.size.height);
        _arrowIndicator.frame = CGRectMake(self.frame.size.width-self.frame.origin.x-_arrowIndicator.frame.size.width-3,(self.frame.size.height -_arrowIndicator.frame.size.height)/2,10,10);
    
        _titleDetail.frame = CGRectMake(self.titleLabel.frame.origin.x-10,self.frame.size.height/4,_arrowIndicator.frame.origin.x-self.titleLabel.frame.origin.x,_titleDetail.frame.size.height);
    

        if ( _titleDetail.text.length != 0 && [[_titleDetail.text substringFromIndex:_titleDetail.text.length-1] isEqualToString:@"元"])
        {
            _titleDetail.textColor = [_selectedItem lookupDetailTitleColor];
            NSString *titleDetailStr = [NSString stringWithFormat:@"%@",_titleDetail.text];
            
            NSMutableAttributedString *titleDetailMutAttStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",titleDetailStr]];
            [titleDetailMutAttStr addAttribute:NSForegroundColorAttributeName value:[_selectedItem lookupDetailTitleColor] range:NSMakeRange(0, titleDetailStr.length-1)];
            [titleDetailMutAttStr addAttribute:NSForegroundColorAttributeName value:self.titleLabel.textColor range:NSMakeRange(titleDetailStr.length-1, 1)];
 
            _titleDetail.attributedText = titleDetailMutAttStr;
        }
        else{
            _titleDetail.textColor = [_selectedItem lookupDetailTitleColor];
        }
        

      
    }
    else{
//        CGFloat x = CGRectGetMidX(self.bounds) +[title sizeWithMyFont:self.titleLabel.font].width/2-5;
//        _arrowIndicator.frame = CGRectMake(x + 20 +self.titleEdgeInsets.left - self.titleEdgeInsets.right,CGRectGetMidY(self.bounds) - 4 + self.titleEdgeInsets.top/2 - self.titleEdgeInsets.bottom/2,10,10);
        
//        self.titleLabel.frame = CGRectMake(self.frame.origin.x +3,self.frame.size.height/3,self.titleLabel.frame.size.width,self.titleLabel.frame.size.height);
        self.titleLabel.frame = CGRectMake(10,self.titleLabel.frame.origin.y,self.titleLabel.frame.size.width,self.titleLabel.frame.size.height);
        
        _arrowIndicator.frame = CGRectMake(self.frame.size.width-_arrowIndicator.frame.size.width-10,(self.frame.size.height -_arrowIndicator.frame.size.height)/2,10,10);
    }

}

-(void)openLookup
{
	[_lookupVC showDropdownViewBelowView:self];
	[self openAnimation];
}

-(void)openAnimation
{
	CABasicAnimation *openRotationAnimation;
	openRotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
	openRotationAnimation.fromValue = 0;
	openRotationAnimation.toValue = [NSNumber numberWithFloat:M_PI];
	openRotationAnimation.duration = 0.15f;
	openRotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	[openRotationAnimation setRemovedOnCompletion:NO];
	[openRotationAnimation setFillMode:kCAFillModeForwards];
	[_arrowIndicator.layer addAnimation:openRotationAnimation forKey:@"openRotationAnimation"];

	_isOpened = !_isOpened;
}

-(void)closeLookup
{
	[_lookupVC dismiss];
	[self closeAnimation];
}

-(void)closeAnimation
{
	CABasicAnimation *closeRotationAnimation;
	closeRotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
	closeRotationAnimation.fromValue = [NSNumber numberWithFloat:M_PI];
	closeRotationAnimation.toValue = 0;
	closeRotationAnimation.duration = 0.15f;
	closeRotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	[closeRotationAnimation setRemovedOnCompletion:NO];
	[closeRotationAnimation setFillMode:kCAFillModeForwards];
	[_arrowIndicator.layer addAnimation:closeRotationAnimation forKey:@"closeRotationAnimation"];
	
	_isOpened = !_isOpened;
}
@end
